package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	unMarshalStruct()
	//unMarshalMap()
	//unMarshalSlice()
	//unMarshalComplexMap()
}

func unMarshalStruct() {
	fmt.Println("-----------------unMarshalStruct-----------------")

	var jsonStr string = formatStruct()
	var monster Monster
	err := json.Unmarshal([]byte(jsonStr), &monster)
	if err != nil {
		fmt.Println("Unmarshal err=", err)
	}
	fmt.Println(monster)

}

func unMarshalMap() {
	fmt.Println("-----------------unMarshalMap-----------------")
	var jsonstr string = "{\"1\":\"zhangsan\",\"2\":\"lisi\",\"3\":\"wangwu\"}"
	var m1 map[string]string
	err := json.Unmarshal([]byte(jsonstr), &m1)
	if err != nil {
		fmt.Println("Unmarshal err=", err)
	}
	fmt.Println(m1)
}

func unMarshalSlice() {
	fmt.Println("-----------------unMarshalSlice-----------------")
	var jsonStr string = "[{\"Name\":\"tom\",\"AGE\":11,\"addr\":\"beijing\"}," +
		"{\"Name\":\"jack\",\"AGE\":13,\"addr\":\"cq\"}," +
		"{\n\"Name\":\"rose\",\"AGE\":18,\"addr\":\"nanjing\"}]"
	var slice []Student
	err := json.Unmarshal([]byte(jsonStr), &slice)
	if err != nil {
		fmt.Println("Unmarshal err=", err)
	}
	fmt.Println(slice) //[{tom 11 beijing} {jack 13 cq} {rose 18 nanjing}]
}

// unMarshalComplexMap
//
//	@Description:
func unMarshalComplexMap() {
	fmt.Println("-----------------unMarshalComplexMap-----------------")
	var str string = "{\"no-001\":\"my name is tom\",\"no-002\":55,\"no-003\":{\"001\":{\"Name\":\"jack\",\"AGE\":20,\" addr\":\"chongqing\"},\"002\":{\"Name\":\"rose\",\"AGE\":19,\"addr\":\"uk\"}}}"
	var m1 map[string]interface{}
	err := json.Unmarshal([]byte(str), &m1)
	if err != nil {
		fmt.Println("Unmarshal err=", err)
	}
	fmt.Println(m1)
}

type Monster struct {
	Name  string `json:"Name"`
	Age   int    `json:"AGE"`
	Addr  string `json:"addr"`
	Skill string `json:"Skill"`
}

// @Description: json marshal
func formatStruct() string {
	var st Monster = Monster{
		Name:  "tristan",
		Addr:  "重庆",
		Age:   30,
		Skill: "芭蕉扇",
	}
	jsonSlice, err := json.Marshal(st)
	if err != nil {
		fmt.Println("json marshal err=-", err)
		return ""
	}
	return string(jsonSlice)
}

type Student struct {
	Name string `json:"Name"`
	Age  int    `json:"AGE"`
	Addr string `json:"addr"`
}
